//
//  PywCouponView.m
//  PywSdk
//
//  Created by Jade on 16/8/25.
//  Copyright © 2016年 zero. All rights reserved.
//

#import "PywCouponView.h"
#import "PywMasonry.h"
#import "ShowCouponsCell.h"
#import "PywCouponListApi.h"
#import "PywMBProgressHUD+Pyw.h"
#import "PywCoupon.h"
#import "PywMJRefresh.h"

@interface PywCouponView()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) UITableView *mainTable;
@property (nonatomic,strong) NSMutableArray *allCoupons;
@property (nonatomic,assign) NSInteger status;
@property (nonatomic,assign) NSInteger page;
@property (nonatomic,strong) PywCouponListApi *couponListApi;

@property (nonatomic,strong) UILabel *promptLabel;
@end

@implementation PywCouponView

- (instancetype)initWithStatus:(NSInteger)status
{
    self = [super init];
    if (self) {
        self.status = status;
        [self setUp];
    }
    return self;
}

#pragma mark - setUp

- (void)setUp
{
    self.backgroundColor = UIColorFromRGB(0xEBEBEC);
    _page = 1;
    _allCoupons = [[NSMutableArray alloc] init];
    [self addSubview:self.mainTable];
    [self addSubview:self.promptLabel];
    [self addConstraints];
    
    [self requestCouponListData];
}

- (void)addConstraints
{
    [self.mainTable mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    WEAK_SELF;
    [self.promptLabel mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.centerX.equalTo(weakSelf.mas_centerX);
        make.centerY.equalTo(weakSelf.mas_centerY);
    }];
}

#pragma mark - getter

- (PywCouponListApi *)couponListApi
{
    if (!_couponListApi) {
        _couponListApi = [PywCouponListApi manager];
    }
    return _couponListApi;
}

- (UITableView *)mainTable
{
    if (!_mainTable) {
        _mainTable = [[UITableView alloc] initWithFrame:CGRectZero
                                                  style:UITableViewStylePlain];
        _mainTable.backgroundColor = [UIColor clearColor];
        _mainTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        _mainTable.delegate = self;
        _mainTable.dataSource = self;
        _mainTable.mj_header.automaticallyChangeAlpha = YES;
        WEAK_SELF;
        _mainTable.mj_header = [PywMJRefreshNormalHeader headerWithRefreshingBlock:^{
            weakSelf.page = 1;
            [weakSelf requestCouponListData];
        }];
        _mainTable.mj_footer = [PywMJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            weakSelf.page ++;
            [weakSelf requestCouponListData];
        }];
    }
    return _mainTable;
}

- (UILabel *)promptLabel
{
    if (!_promptLabel) {
        _promptLabel = [UILabel new];
        _promptLabel.font = [UIFont systemFontOfSize:15.f];
        _promptLabel.text = @"没有数据";
        _promptLabel.hidden = YES;
        _promptLabel.textColor = [UIColor grayColor];
    }
    return _promptLabel;
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.allCoupons.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80.f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 10.f;
    }
    return 0.01f;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifter = @"Cell";
    ShowCouponsCell *cell = [tableView dequeueReusableCellWithIdentifier:identifter];
    if (cell == nil) {
        cell = [[ShowCouponsCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:identifter];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    PywCoupon *coupon = [self.allCoupons objectAtIndex:indexPath.section];
    if (self.status == 2) {
        coupon.isChoose = YES;
    }
    cell.coupon = coupon;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - Actions
/**
 *  隐藏显示没有数据提示
 */
- (void)hideShowPromptLabel
{
    self.promptLabel.hidden = YES;
    if (self.allCoupons.count == 0) {
        self.promptLabel.hidden = NO;
    }
}

/**
 *  请求代金券列表
 */
- (void)requestCouponListData
{
    WEAK_SELF;
    [PywMBProgressHUD showMessage:@"正在加载代金券..." toView:self];
    [self.couponListApi getCouponListWithStatus:self.status page:self.page success:^(NSString *status, id anyObjct) {
        STRONG_SELF(weakSelf);
        [strongSelf.mainTable.mj_header endRefreshing];
        [strongSelf.mainTable.mj_footer endRefreshing];
        [PywMBProgressHUD hideHUDForView:strongSelf];
        NSDictionary *orderDict = (NSDictionary *)anyObjct;
        NSDictionary *data = [orderDict objectForKey:@"data"];
        NSInteger ack = [[orderDict objectForKey:@"ack"] integerValue];
        if (ack == 200) {
            NSArray *list = [data objectForKey:@"list"];
            NSArray *coupons = [PywCoupon arrayOfModelsFromDictionaries:list error:nil];
            if (strongSelf.page == 1) {
                [strongSelf.allCoupons setArray:coupons];
                [self itemTitles:data];
            }else {
                [strongSelf.allCoupons addObjectsFromArray:coupons];
            }
            [strongSelf.mainTable reloadData];
            
            NSInteger total_pages = [[data objectForKey:@"total_pages"] integerValue];
            if (strongSelf.page >= total_pages) {
                [strongSelf.mainTable.mj_footer setHidden:YES];
            }else {
                [strongSelf.mainTable.mj_footer setHidden:NO];
            }
        }
        
        [strongSelf hideShowPromptLabel];
        
    } fail:^(NSError *error) {
        [PywMBProgressHUD hideHUDForView:weakSelf];
        [PywMBProgressHUD showError:@"获取代金券失败"];
        [weakSelf hideShowPromptLabel];
    }];
}

- (void)itemTitles:(NSDictionary *)dict
{
    NSString *num_not_use = [dict objectForKey:@"num_not_use"];
    NSString *num_have_used = [dict objectForKey:@"num_have_used"];
    NSString *num_expire = [dict objectForKey:@"num_expire"];
    NSArray *array = @[[NSString stringWithFormat:@"未使用(%@)",num_not_use],
                       [NSString stringWithFormat:@"已使用(%@)",num_have_used],
                       [NSString stringWithFormat:@"已过期(%@)",num_expire]];
    if (self.backTitlesComplete) {
        self.backTitlesComplete(array);
    }
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
